﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Data.OleDb;
using Aandelendelen.Obs;
using Aandelendelen.Db;

namespace Aandelendelen.Daily
{
	public class EndOfYear : DailyJob
	{
		public EndOfYear(XmlNode jobNode)
			: base(jobNode, "Handling end of year...")
		{ }

		public override void Execute()
		{
			this.OnStart();

			try
			{
				this.AdjustCredits();
			}
			catch (Exception e)
			{
				this.OnError(e);
			}

			this.OnEnd();
		}

		private void AdjustCredits()
		{
			/*
			int year = DateTime.Today.Year;

			int oudejaarsTrekking = (year - 2000) * 14 + 13;

			Query query = new Query("s_getpositivecredits", "trekking", oudejaarsTrekking, OleDbType.Integer);
			Query saldoQuery = new Query("s_getsaldoforyearcorrection", "trekking", oudejaarsTrekking, OleDbType.Integer);

			//both queries should have the same Count.
			ResultSet resultSet = (ResultSet)query.Execute();
			ResultSet saldoResultSet = (ResultSet)saldoQuery.Execute();

			int count = resultSet.Count;

			for (int i = 0; i < count; i++)
			{
				int nawId = (int)resultSet[i, "NawId"];
				decimal totSaldo = (decimal)resultSet[i, "totalsaldo"];

				decimal heffing = Calculator.GetCommission(totSaldo);

				decimal saldo = (decimal)saldoResultSet[i, "saldo"];

				Userinfo userInfo = new Userinfo(resultSet, i, false);
				userInfo.Id = nawId;

				if (heffing > saldo)
				{
					decimal betReduction = heffing - saldo;

					//Get future bets for nawId
					QueryArguments args = new QueryArguments();

					args.Add("NawId", nawId, OleDbType.Integer);
					args.Add("Trekking", oudejaarsTrekking, OleDbType.Integer);

					Query betQuery = new Query("s_getfuturebets", args);

					ResultSet betResultSet = (ResultSet)betQuery.Execute();

					int betNumber = 0;
					while (betReduction > 0 && betNumber < betResultSet.Count)
					{
						decimal oldBet = -(decimal)betResultSet[betNumber, "Bedrag"];
						decimal newBet = oldBet;

						if (oldBet >= betReduction)
						{
							newBet -= betReduction;
							betReduction = 0;
						}
						else
						{
							betReduction -= oldBet;
							newBet = 0;

							betNumber++;
						}

						BetHandler betHandler = new BetHandler(userInfo, -oldBet, -newBet, (int)betResultSet[betNumber, "Trekking"], this.queries);

						betHandler.Handle();
					}
				}

				this.MutateBalance(heffing, nawId);
			}*/
		}

		private void MutateBalance(decimal heffing, int nawId)
		{
			CommonQueries.InsertSaldoMutation(nawId, -heffing, -3, 0, this.queries);
		}
	}
}